package com.example.okhttp.net

import com.example.okhttp.test.TEST_RN_URL
import com.example.okhttp.util.DecryptionConverter
import com.example.okhttp.util.EncryptionConverter
import com.example.okhttp.util.HeaderInterceptor
import com.example.okhttp.util.createLogInterceptor
import okhttp3.OkHttpClient
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Converter
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

// Retrofit工厂类
object RetrofitFactory {
    // 创建自定义转换器工厂
    private inline fun <reified REQUEST, RESPONSE> createCustomConverter(
        requestConverter: Converter<REQUEST, RequestBody>,
        responseConverter: Converter<ResponseBody, RESPONSE>
    ) = object : Converter.Factory() {
        override fun requestBodyConverter(
            type: java.lang.reflect.Type,
            parameterAnnotations: Array<Annotation>,
            methodAnnotations: Array<Annotation>,
            retrofit: Retrofit
        ) = requestConverter as Converter<*, RequestBody>?

        override fun responseBodyConverter(
            type: java.lang.reflect.Type,
            annotations: Array<Annotation>,
            retrofit: Retrofit
        ) = responseConverter as Converter<ResponseBody, *>?
    }

    val apiService: ApiService by lazy {
        val okHttpClient = OkHttpClient.Builder()
            .addInterceptor(HeaderInterceptor())
            .addInterceptor(createLogInterceptor())
            .build()

        Retrofit.Builder()
            .baseUrl(TEST_RN_URL)
            .client(okHttpClient)
            .addConverterFactory(createCustomConverter(
                requestConverter = EncryptionConverter(),
                responseConverter = DecryptionConverter()
            ))
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(ApiService::class.java)
    }
}